package com.fjzx.androidframe.base.widget.xrecyclerview;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author xiongyongcong
 */
public class RecyclerViewFabBehavior extends FloatingActionButton.Behavior {
    public RecyclerViewFabBehavior() {
    }

    public RecyclerViewFabBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull FloatingActionButton child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type);
    }

    @Override
    public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull FloatingActionButton child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
        if (target instanceof RecyclerView) {
            RecyclerView recyclerView = (RecyclerView) target;
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            int lastPosition = layoutManager.findLastVisibleItemPosition();
            if (lastPosition < recyclerView.getAdapter().getItemCount() - 1) {
                if (dyConsumed >= 0 && child.getVisibility() == View.VISIBLE) {
                    child.setVisibility(View.INVISIBLE);
                } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
                    child.setVisibility(View.VISIBLE);
                }
            } else {
                child.setVisibility(View.INVISIBLE);
            }
        }
    }
}
